package com.xhwl.logistics.open;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.logistics.bo.cent.ProjectBO;
import com.xhwl.logistics.bo.cent.VehicleIntegratedConfigBO;
import com.xhwl.logistics.dto.push.*;
import com.xhwl.logistics.entity.VehicleAccessRecord;
import com.xhwl.logistics.entity.VehiclePayRecord;
import com.xhwl.logistics.service.cent.QueryDeviceService;
import com.xhwl.logistics.service.cent.QueryProjectService;
import com.xhwl.logistics.service.impl.VehicleAccessRecordServiceImpl;
import com.xhwl.logistics.service.impl.VehiclePayRecordServiceImpl;
import com.xhwl.logistics.util.DateFormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

/**
 * @Description: 立方缴费记录和出入记录接口 提供给第三方
 * @Author:wangyiling
 * @Date:2023/04/21
 */
@Slf4j
//@RestController
public class LiFangDataPushController {

    @Autowired
    private QueryProjectService queryProjectService;

    @Autowired
    private QueryDeviceService queryDeviceService;

    @Autowired
    private VehicleAccessRecordServiceImpl vehicleAccessRecordService;

    @Autowired
    private VehiclePayRecordServiceImpl vehiclePayRecordService;

    @PostMapping("/lifang/carRecord")
    public JSONObject carRecord(@RequestBody CarRecordLiFangDTO carDTO) {
        log.info("lifang push carOut start!");
        log.info("carOutDTO: " + carDTO);
        HashMap<String, Object> response = new HashMap<>();
        response.put("resCode", 0);//保存成功
        response.put("resMsg", "成功");
        VehicleIntegratedConfigBO vehicleIntegratedConfigBO = getLiFangConfig();
        if(vehicleIntegratedConfigBO.getVehicleSystemInfoBO()!=null && vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId() != null) {
            ProjectBO projectBO = queryProjectService.queryProject(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
            if(projectBO == null){
                response.put("resCode", 1);//保存失败
                response.put("resMsg", "项目未集成立方车场，出入记录保存失败");
                return JSONObject.parseObject(JSONObject.toJSONString(response));
            }
            if (StringUtils.isNotEmpty(carDTO.getCarCode()) && StringUtils.isNotEmpty(carDTO.getPassTime())) {
                VehicleAccessRecord vehicleAccessRecord = new VehicleAccessRecord();
                vehicleAccessRecord.setRecordId(carDTO.getGUID());
                vehicleAccessRecord.setPlateNumber(carDTO.getCarCode());
                vehicleAccessRecord.setParkId(carDTO.getParkID());
                vehicleAccessRecord.setProjectId(projectBO.getProjectId());
                vehicleAccessRecord.setProjectName(projectBO.getProjectName());
                vehicleAccessRecord.setStatus(Integer.parseInt(carDTO.getInOrOut()));
                String imageUrl = "";
                if(StringUtils.isNotEmpty(carDTO.getImagePath())){
                    int index = carDTO.getImagePath().indexOf("\\Capture_Images");
					if(index>0){
                    	imageUrl =vehicleIntegratedConfigBO.getVehicleParkingInfoBO().getHost()+carDTO.getImagePath().substring(index);
                	}
				}
                if (carDTO.getInOrOut().equals("0")) {
                    vehicleAccessRecord.setEnterPassageName(carDTO.getChannelName());
                    vehicleAccessRecord.setEnterPassageId(Integer.parseInt(carDTO.getChannelID()));
                    vehicleAccessRecord.setEnterTime(DateFormatUtil.stringDate2Date(carDTO.getPassTime()));
                    vehicleAccessRecord.setEnterPictureUrl(imageUrl);
                } else {
                    vehicleAccessRecord.setExitPassageName(carDTO.getChannelName());
                    vehicleAccessRecord.setExistPassageId(Integer.parseInt(carDTO.getChannelID()));
                    vehicleAccessRecord.setExitTime(DateFormatUtil.stringDate2Date(carDTO.getPassTime()));
                    vehicleAccessRecord.setExitPictureUrl(imageUrl);
                }


                //对出入记录进行去重处理，即存在就更新，不存在就新增
                List<VehicleAccessRecord> vehicleAccessRecordList = vehicleAccessRecordService.list(new LambdaQueryWrapper<VehicleAccessRecord>().eq(VehicleAccessRecord::getProjectId, projectBO.getProjectId())
                        .eq(VehicleAccessRecord::getRecordId, carDTO.getGUID()));
                if(vehicleAccessRecordList.isEmpty()){
                    vehicleAccessRecordService.save(vehicleAccessRecord);
                }else{
                    vehicleAccessRecord.setId(vehicleAccessRecordList.get(0).getId());
                    vehicleAccessRecordService.updateById(vehicleAccessRecord);
                }
            } else {
                response.put("resCode", 1);//保存失败
                response.put("resMsg", "车牌号为空或者进出时间为空");
            }
        }
        log.info("lifang push carOut end!");
        return JSONObject.parseObject(JSONObject.toJSONString(response));
    }

    @PostMapping("/lifang/carPay")
    public JSONObject carPay(@RequestBody CarPayLiFangDTO carDTO) {
        log.info("lifang push carOut start!");
        log.info("carOutDTO: " + carDTO);
        HashMap<String, Object> response = new HashMap<>();
        response.put("resCode", 0);//保存成功
        response.put("resMsg", "成功");
        VehicleIntegratedConfigBO vehicleIntegratedConfigBO = getLiFangConfig();
        if(vehicleIntegratedConfigBO.getVehicleSystemInfoBO()!=null && vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId() != null) {
            ProjectBO projectBO = queryProjectService.queryProject(vehicleIntegratedConfigBO.getVehicleSystemInfoBO().getProjectId());
            if(projectBO == null){
                response.put("resCode", 1);//保存失败
                response.put("resMsg", "项目未集成立方车场，消费记录保存失败");
                return JSONObject.parseObject(JSONObject.toJSONString(response));
            }
            if (StringUtils.isNotEmpty(carDTO.getCarCode()) && StringUtils.isNotEmpty(carDTO.getPayTime()) && StringUtils.isNotEmpty(carDTO.getInTime())) {
                VehiclePayRecord vehiclePayRecord = new VehiclePayRecord();
                vehiclePayRecord.setPlateNumber(carDTO.getCarCode());
                vehiclePayRecord.setParkId(carDTO.getParkID());
                vehiclePayRecord.setProjectId(projectBO.getProjectId());
                vehiclePayRecord.setPayTime(DateFormatUtil.stringDate2Date(carDTO.getPayTime()));
                vehiclePayRecord.setEnterTime(DateFormatUtil.stringDate2Date(carDTO.getInTime()));
                vehiclePayRecord.setPayMethod(carDTO.getChargeType());
                vehiclePayRecord.setPayRecordId(carDTO.getRecordID());
                vehiclePayRecord.setPaidMoney(carDTO.getPaidMoney());
                vehiclePayRecord.setFreeMoney(carDTO.getJMMoney());
                vehiclePayRecord.setTotalMoney(carDTO.getChargeMoney());
                vehiclePayRecord.setCreatedAt(new Date());
                vehiclePayRecord.setUpdatedAt(new Date());
                //对缴费记录进行去重处理，即存在就更新，不存在就新增
                List<VehiclePayRecord> vehiclePayRecordList = vehiclePayRecordService.list(new LambdaQueryWrapper<VehiclePayRecord>().eq(VehiclePayRecord::getProjectId, projectBO.getProjectId())
                        .eq(VehiclePayRecord::getAccessRecordId, carDTO.getRecordID()));
                if(vehiclePayRecordList.isEmpty()){
                    vehiclePayRecordService.save(vehiclePayRecord);
                }else{
                    vehiclePayRecord.setId(vehiclePayRecordList.get(0).getId());
                    vehiclePayRecordService.updateById(vehiclePayRecord);
                }
            } else {
                response.put("resCode", 1);//保存失败
                response.put("resMsg", "车牌号为空或者支付时间为空");
            }
        }
        log.info("lifang push carOut end!");
        return JSONObject.parseObject(JSONObject.toJSONString(response));
    }

    /**
     * 获取大华ICC的项目id
     */
    private VehicleIntegratedConfigBO getLiFangConfig(){

        //获取所有车场系统对应的集成配置
        List<VehicleIntegratedConfigBO> vehicleIntegratedConfigBOList = queryDeviceService.queryIntegratedConfigs();
        VehicleIntegratedConfigBO vehicleIntegratedConfigBO = vehicleIntegratedConfigBOList.stream().filter(s -> {
            if(s.getVehicleSystemInfoBO().getProductId() != null && s.getVehicleSystemInfoBO().getProductId() == ProductEnum.LIFANG_VEHICLE.getId()){
                return true;
            }
            return false;
        }).findAny().orElse(null);
        if(vehicleIntegratedConfigBO!=null){
            return vehicleIntegratedConfigBO;
        }else{
            log.info("未给立方配置集成配置！");
            return new VehicleIntegratedConfigBO();
        }
    }
}
